package com.shiro.web.realm;

import java.text.MessageFormat;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.shiro.web.model.Permission;
import com.shiro.web.service.PermService;

public class ChainDefinitionSectionMetaSource implements
		FactoryBean<Ini.Section> {

	public static final String PERMISSION_STRING = "perms[\"{0}\"]";

	private String filterChainDefinitions;

	@Autowired
	private PermService permService;

	@Autowired
	public void setFilterChainDefinitions(String filterChainDefinitions) {
		List<Permission> perms = permService.getPermissions();
		StringBuilder builder = new StringBuilder();
		for (Permission permission : perms) {
			String url = permission.getUrl();
			if (url != null && !"".equals(url)) {
				builder.append(url + " = authc,");
				builder.append(MessageFormat.format(PERMISSION_STRING, permission.getPerm()));
				builder.append("\n");
			}
		}
		filterChainDefinitions += builder.toString();
		Logger.getLogger(this.getClass()).info(filterChainDefinitions);
		this.filterChainDefinitions = filterChainDefinitions;
	}

	@Override
	public Section getObject() throws Exception {
		Ini ini = new Ini();
		ini.load(filterChainDefinitions);
		Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
		return section;
	}

	@Override
	public Class<?> getObjectType() {
		return this.getClass();
	}

	@Override
	public boolean isSingleton() {
		// TODO Auto-generated method stub
		return false;
	}

}
